/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package edu.lnu.ums.dal.impl;

import edu.lnu.ums.dal.IGenericProcessDAO;
import edu.lnu.ums.entities.core.AbstractProcess;
import edu.lnu.ums.entities.core.UMSObject;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;

public class GenericProcessDAO<T extends AbstractProcess> extends AbstractConcurrentAccessGenericDAO<T> implements IGenericProcessDAO<T>{

    public GenericProcessDAO(Class<T> cls) {
        super(cls);
    }

    @Override
    public void delete(T obj) {
        throw new UnsupportedOperationException("No need to delete process!");
    }

    @Override
    public String getOrderByQuery() {
        return "";
    }

    @Override
    public AbstractProcess getByClassAndTargetObject(Class<?> clazz, UMSObject object) {
        EntityManager em = object.getFactory().createEntityManager();
        
        List<AbstractProcess> list = em.createQuery("from " + clazz.getSimpleName() + " p where p.targetEnity.id = "
                + object.getId().toString()).getResultList();
        
        if (list.size() == 0) {
            try {
                AbstractProcess newInst = (AbstractProcess) clazz.newInstance();
                newInst.setTargetEnity(object);
                setEntityManagerFactoryToEntity(object.getFactory(), newInst);
                return newInst;
            } catch (InstantiationException ex) {
                ex.printStackTrace();
                return null;
            } catch (IllegalAccessException ex) {
                ex.printStackTrace();
                return null;
            }
        }

        if (list.size() == 1) {
            AbstractProcess proc = list.get(0);
            setEntityManagerFactoryToEntity(object.getFactory(), proc);
            return proc;
        }

        throw new IllegalStateException("There can not be two same processes for one umsobject!");
    }
}
